﻿using UnityEngine;
using UnityEngine.UI;

public class Square : MonoBehaviour
{
    public Location location;
    public int x => location.x;
    public int y => location.y;
    public SquareType type;
    public Camp camp;
    public Chessman Chessman => Chessman.GetChessman(location);//通过此属性，可以访问位于此方格上的棋子

    private void Start()
    {
        GetComponent<Button>().onClick.AddListener(OnSquareClicked);
    }

    public override string ToString()
    {
        return $"棋盘方格坐标:{location},地形类型:{type},阵营:{camp}";
    }

    public void OnSquareClicked()
    {
        var selection = SelectCore.Selection;
        //玩家手里有子
        if (selection)
        {
            //点击空方格
            if (!Chessman)
            {
                CommandCenter.GameOrder(selection, location);
            }
            //点击有己方棋子的方格
            else if (Chessman.camp == PlayerManager.Get.currentPlayer)
            {
                SelectCore.TrySelect(Chessman);
            }
            //点击有对方棋子的方格
            else
            {
                CommandCenter.GameOrder(selection, location);
            }
        }
        //玩家手里无子
        else
        {
            //点击空方格
            if (!Chessman)
            {
                return;
            }
            //点击有己方棋子的方格
            else if (Chessman.camp == PlayerManager.Get.currentPlayer)
            {
                SelectCore.TrySelect(Chessman);
            }
            //点击有对方棋子的方格
            else
            {
                return;
            }
        }
    }

    /// <summary>
    /// 移除棋盘方格上的棋子(如果有的话)。
    /// </summary>
    public void RemoveChessman()
    {
        if (Chessman != null)
        {
            Chessman.ExitFromBoard();
        }
    }
}